﻿// -----------------------------------------------------------------------
// <copyright file="ExtentionMethods.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace BasicFrameworkDemo.Utility
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Web.Script.Serialization;
    using System.Xml.Serialization;

    using NHibernate;
    using NHibernate.Linq;

    /// <summary>
    /// Extention methods
    /// </summary>
    public static class ExtentionMethods
    {
        /// <summary>
        /// Determines whether [is null or empty] [the specified obj].
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns>
        ///   <c>true</c> if [is null or empty] [the specified obj]; otherwise, <c>false</c>.
        /// </returns>
        /// Creator:LiLei
        /// CreationDate:7/11/2012 2:24 PM
        /// Modify:
        /// ModifyDate:
        /// ----------------------------------------------------------------------------------------
        public static bool IsNullOrEmpty(this object obj)
        {
            if (obj == null)
            {
                return true;
            }

            return obj.ToString().Trim().Length == 0;
        }

        /// <summary>
        /// Gets the error message.
        /// </summary>
        /// <param name="errorCode">The error code.</param>
        /// <returns></returns>
        /// Creator:LiLei
        /// CreationDate:12/6/2012 12:00 PM
        /// Modify:
        /// ModifyDate:
        /// ----------------------------------------------------------------------------------------
        public static string GetErrorMessage(this string errorCode)
        {
            if (errorCode.IsNullOrEmpty())
                return string.Empty;
            var errorsDictionary = SystemErrors.GetInstance().ErrorsDictionary;
            return errorsDictionary.ContainsKey(errorCode) ? errorsDictionary[errorCode] : string.Empty;
        }

        #region Json Serialize and Deserialize

        /// <summary>
        /// Serializes the specified obj.
        /// </summary>
        /// <typeparam name="TType">The type of the type.</typeparam>
        /// <param name="obj">The obj.</param>
        /// <returns></returns>
        /// Creator:LiLei
        /// CreationDate:7/15/2012 2:59 PM
        /// Modify:
        /// ModifyDate:
        /// ----------------------------------------------------------------------------------------
        public static string Serialize<TType>(this TType obj)
        {
            if (obj.IsNullOrEmpty())
            {
                return string.Empty;
            }

            if (obj.GetType().Name.Contains("<>f__AnonymousType"))
            {
                var serializer = new JavaScriptSerializer();
                return serializer.Serialize(obj);
            }

            using (var ms = new MemoryStream())
            {
                var serializer = new DataContractJsonSerializer(obj.GetType(), new List<Type>(), int.MaxValue, true, null, false);
                serializer.WriteObject(ms, obj);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }


        /// <summary>
        /// Deserializes the specified json.
        /// </summary>
        /// <typeparam name="TType">The type of the type.</typeparam>
        /// <param name="json">The json.</param>
        /// <returns></returns>
        /// Creator:LiLei
        /// CreationDate:7/15/2012 2:59 PM
        /// Modify:
        /// ModifyDate:
        /// ----------------------------------------------------------------------------------------
        public static TType Deserialize<TType>(this string json)
        {
            var model = Activator.CreateInstance<TType>();
            if (string.IsNullOrEmpty(json) || string.IsNullOrWhiteSpace(json))
            {
                return model;
            }

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                var serializer = new DataContractJsonSerializer(model.GetType(), new List<Type>(), int.MaxValue, true, null, false);
                return (TType)serializer.ReadObject(ms);
            }
        }


        /// <summary>
        /// Deserializes the specified json.
        /// </summary>
        /// <param name="json">The json.</param>
        /// <returns></returns>
        /// Creator:LiLei
        /// CreationDate:7/15/2012 2:59 PM
        /// Modify:
        /// ModifyDate:
        /// ----------------------------------------------------------------------------------------
        public static string Deserialize(this string json)
        {
            if (string.IsNullOrEmpty(json) || string.IsNullOrWhiteSpace(json))
            {
                return string.Empty;
            }

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                var serializer = new DataContractJsonSerializer(typeof(string));
                return (string)serializer.ReadObject(ms);
            }
        }

        #endregion

        #region Xml Serialize and Deserialize
        public static TType XmlDeserialize<TType>(this string xml)
        {
            var xs = new XmlSerializer(typeof(TType));
            var tr=new StringReader(xml);
            var obj = (TType)xs.Deserialize(tr);
            tr.Close();
            return obj;
        }
        #endregion

        #region Write log

        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="message">The value of the message.</param>
        /// <param name="logType">Type of the log.</param>
        /// Creator:zhouchao
        /// Creation Date:10/14/2011 8:59 AM
        /// Modifier:
        /// Last Modified:
        /// ----------------------------------------------------------------------------------------
        public static void WriteLog(this string message, Log4NetType logType)
        {
            var log = Log4NetUtility.GetInstance().GetLogger(SystemConfig.ApplicationLogger);
            if (logType == Log4NetType.Debug)
            {
                log.Debug(message);
                return;
            }

            if (logType == Log4NetType.Error)
            {
                log.Error(message);
                return;
            }

            if (logType == Log4NetType.Fatal)
            {
                log.Debug(message);
                return;
            }

            if (logType == Log4NetType.Info)
            {
                log.Info(message);
                return;
            }

            log.Warn(message);
        }

        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="exception">The value of the exception.</param>
        /// Creator:zhouchao
        /// Creation Date:11/14/2011 11:35 AM
        /// Modifier:
        /// Last Modified:
        /// ----------------------------------------------------------------------------------------
        public static void WriteLog(this Exception exception)
        {
            var log = Log4NetUtility.GetInstance().GetLogger(SystemConfig.ApplicationLogger);
            log.Error(exception);
        }

        #endregion
    }
}
